#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <cstdio>
#include <sys/wait.h>

using namespace std;

int main()
{
	int pip[2];
	if(pipe(pip)==-1)
	{
		perror("open pipe error");
		exit(-1);
	}
	pid_t id=fork();
	if(id<0)
	{
		perror("fork error fail");
		exit(-1);
	}
	else if(id==0)
	{
		//子进程
		close(pip[0]);//读段关闭
		int cnt=0;
		while(cnt<10)
		{
			char buffer[1024];
			snprintf(buffer,1024,"hello i am writor:%d,num=%d",getpid(),cnt);
			write(pip[1],buffer,sizeof(buffer));
		}
	}
	else
	{
		close(pip[1]);
		char buffer[1024];
		while(true)
		{
			sleep(10);
			ssize_t n =read(pip[0],buffer,sizeof(buffer)-1);
			if(n>0)
			{
				buffer[n]=0;
				cout<<getpid()<<','<<"child say:"<<buffer<<"to me!"<<endl;
			}
			else if(n==0)
			{
				cout<<"child quit,me too!"<<endl;
				break;
			}
			cout<<"father return val(n)"<<n<<endl;
			sleep(1);
			break;
			
		}
		close(pip[0]);
		int status;
		waitpid(id,&status,0);
	}

	return 0;
}
